package com.gin.kotlin.no_gay_alliance.provider.ngaphp

import android.content.Context
import android.content.DialogInterface
import android.widget.RadioButton
import android.widget.RadioGroup
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.base.AlertDialogUtils
import com.gin.kotlin.no_gay_alliance.callback.RCallback
import com.gin.nga.callback.NgaCallback
import com.gin.nga.enums.FavorFolderType
import com.gin.nga.main.NgaApi
import com.gin.nga.response.base.NgaResponse
import com.gin.nga.response.favor.FavorFolder
import com.gin.nga.response.favor.FavorFolderBody
import retrofit2.Call
import retrofit2.Response
import java.lang.ref.WeakReference

/**
 * 收藏夹列表提供者
 * 暂时仅支持对第一页查询
 * @property dir String
 */
class FavorFolderProvider private constructor() : AbstractCachedDataProvider<Long, FavorFolderBody, List<FavorFolder>>(
    javaType = TYPE_FACTORY.constructCollectionLikeType(List::class.java, FavorFolder::class.java)
) {
    override val dir = "FAVOR_FOLDER"
    override fun transform(rawData: FavorFolderBody) = rawData.data ?: listOf()
    override fun requestMethod(ngaApi: NgaApi, params: Long?) = ngaApi.favorApi.folderList(userId = params)
    override fun obtainRelativePath(userId: Long, params: Long?) = "$params.json"

    companion object {
        private var instance: WeakReference<FavorFolderProvider> = WeakReference(FavorFolderProvider())
        fun getInstance(): FavorFolderProvider = instance.get() ?: FavorFolderProvider().also { instance = WeakReference(it) }

        fun showFolderDialog(context: Context, topicId: Long, replyId: Long? = null) {
            getInstance().enqueue(callback = object : RCallback<List<FavorFolder>, Long> {
                override fun onSuccess(data: List<FavorFolder>, ignoreCache: Boolean) {
                    // 如果只有一个收藏夹，直接添加
                    if (data.size == 1) {
                        addFavorTopic(data[0].id!!, topicId, replyId)
                    } else {
                        // 有多个收藏夹，弹窗选择
                        val radioGroup = RadioGroup(context)

                        data.forEach {
                            val rb = RadioButton(context)
                            rb.id = it.id?.toInt()!!
                            rb.text = it.getFullName()
                            radioGroup.addView(rb)
                            if (it.type == FavorFolderType.DEFAULT) radioGroup.check(rb.id)
                        }


                        AlertDialogUtils.builder(context,
                            context.getString(R.string.dialog_title_select_favor_folder),
                            message = context.getString(R.string.dialog_message_select_favor_folder),
                            contentView = radioGroup,
                            listener = { _, which ->
                                if (which == DialogInterface.BUTTON_POSITIVE) {
                                    addFavorTopic(radioGroup.checkedRadioButtonId.toLong(), topicId, replyId)
                                }
                            }).show()
                    }
                }

                override fun onError(errorMessage: String) {
                    App.INSTANCE.handler?.toast(context.getString(R.string.toast_message_error_on_get_favor_folder))
                }
            })
        }

        /**
         * 添加主题到收藏
         * @param folderId 收藏夹ID
         * @param topicId 主题ID
         * @param replyId 回复ID
         */
        fun addFavorTopic(folderId: Long, topicId: Long, replyId: Long? = null) {
            App.INSTANCE.ngaApi.favorApi.add(folderId, topicId, replyId).enqueue(object : NgaCallback<List<String>> {
                override fun onSuccess(
                    call: Call<NgaResponse<List<String>>>, response: Response<NgaResponse<List<String>>>, body: NgaResponse<List<String>>?, data: List<String>?
                ) {
                    data?.get(0)?.also { App.INSTANCE.handler?.toast(it) }
                }

                override fun onError(call: Call<NgaResponse<List<String>>>, response: Response<NgaResponse<List<String>>>, body: NgaResponse<List<String>>?, errorMessage: String) {
                    App.INSTANCE.handler?.toast(errorMessage)
                }
            })
        }
    }
}